<template>
  <div ref="ganttRef" style="width: 100%; height: 100%" id="gantt_here"></div>
  <el-dialog v-model="visible" title="新增任务" width="1200px">
    <slot></slot>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary"> 保存 </el-button>
        <el-button @click="visible = false">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { onMounted, onUnmounted, ref } from 'vue';
import { gantt } from 'dhtmlx-gantt';
import 'dhtmlx-gantt/codebase/dhtmlxgantt.css';

defineOptions({
  name: 'DwGantt',
});
const ganttRef = ref();
const visible = ref(false);
const initGantt = () => {
  const tasks = {
    data: [
      {
        id: '10',
        text: '任务1',
        start_date: '2025-07-09',
        duration: 12,
        order: 10,
        progress: 0.4,
        open: true,
      },
      {
        id: '1',
        text: '子任务1',
        start_date: '2025-07-10',
        duration: 1,
        order: 10,
        progress: 0.6,
        parent: '10',
      },
      {
        id: '2',
        text: '子任务2',
        start_date: '2025-07-12',
        duration: 2,
        order: 20,
        progress: 0.6,
        parent: '10',
      },
      {
        id: '3',
        text: '子任务2',
        start_date: '2025-11-31',
        duration: 2,
        order: 20,
        progress: 0.6,
        parent: '10',
      },
    ],
    links: [{ id: 1, source: 1, target: 2, type: '0' }],
  };
  gantt.plugins({
    quick_info: true,
    marker: true,
    tooltip: true,
  });

  const zoomConfig = {
    levels: [
      {
        name: 'day',
        scale_height: 27,
        column_width: 60,
        scales: [{ unit: 'day', step: 1, format: '%m-%d' }],
      },
      {
        name: 'week',
        scale_height: 50,
        min_column_width: 50,
        scales: [
          {
            unit: 'week',
            step: 1,
            format: function (date: Date) {
              const dateToStr = gantt.date.date_to_str('%d %M');
              const endDate = gantt.date.add(date, 6, 'day');
              const weekNum = gantt.date.date_to_str('%W')(date);
              return '#' + weekNum + ', ' + dateToStr(date) + ' - ' + dateToStr(endDate);
            },
          },
          { unit: 'day', step: 1, format: '%j %D' },
        ],
      },
      {
        name: 'month',
        scale_height: 50,
        min_column_width: 120,
        scales: [
          { unit: 'month', format: '%F, %Y' },
          { unit: 'week', format: 'Week #%W' },
        ],
      },
      {
        name: 'quarter',
        height: 50,
        min_column_width: 90,
        scales: [
          { unit: 'month', step: 1, format: '%M' },
          {
            unit: 'quarter',
            step: 1,
            format: function (date: Date) {
              const dateToStr = gantt.date.date_to_str('%M');
              const endDate = gantt.date.add(gantt.date.add(date, 3, 'month'), -1, 'day');
              return dateToStr(date) + ' - ' + dateToStr(endDate);
            },
          },
        ],
      },
      {
        name: 'year',
        scale_height: 50,
        min_column_width: 30,
        scales: [{ unit: 'year', step: 1, format: '%Y' }],
      },
    ],
  };
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
  //@ts-ignore
  gantt.ext.zoom.init(zoomConfig);

  gantt.config.baselines = true;
  gantt.ext.zoom.setLevel('day');

  // gantt.setSkin("broadway");
  gantt.config.readonly = false; //是否只读
  gantt.i18n.setLocale('cn');
  gantt.config.show_progress = true; //显示进度条
  gantt.config.xml_date = '%Y.%m.%d'; //甘特图时间数据格式
  //设置时间刻度的格式
  // gantt.config.date_scale = "%m月%d日";
  gantt.config.drag_resize = true; //允许拖动任务时调整任务大小
  gantt.config.drag_links = true; //允许拖动任务时调整任务链接
  gantt.config.order_branch = true; //允许拖动任务时保持任务顺序
  gantt.config.drag_progress = true; //允许拖动任务时调整任务进度
  gantt.config.columns = [
    {
      name: 'add',
      label: '',
      width: 30,
      align: 'center',
    },
    {
      name: 'text', //任务名称，
      tree: true, //是否开始tree联级,
      width: 220,
      resize: true,
      label: '任务名称',
      template: (obj) => {
        return obj.text;
      },
      align: 'left',
    },
    // {
    //   name: 'start_date',
    //   label: '开始时间',
    //   width: '110',
    //   align: 'left',
    // },
    // {
    //   name: 'staff',
    //   label: '负责人',
    //   width: 80,
    //   template: (obj) => {
    //     console.log(obj.start_date)
    //     return `张安`
    //   },
    // },
    // {
    //   name: 'end_date',
    //   label: '结束时间',
    //   width: '100',
    //   align: 'left',
    // },
  ];
  const today = new Date(new Date().setHours(0, 0, 0, 0)); // 获取当天零点的时间
  gantt.addMarker({
    start_date: today,
    css: 'today',
    text: '今日',
    title: `Today: ${today}`,
  });
  gantt.showLightbox = function (id) {
    const task = gantt.getTask(id);
    // alert(task.text)
    visible.value = true;
    return false;
  };
  gantt.templates.grid_folder = function (item) {
    console.log(item.$open);
    return `<span class="iconfont dw-jichuxinxi"></span>`;
  };

  gantt.attachEvent(
    'onTaskClick',
    function () {
      console.log('capture next task click');
      return true;
    },
    { once: false },
  );
  gantt.templates.grid_file = function () {
    return `<span class="iconfont">&#xe652;</span>`;
  };
  gantt.templates.quick_info_class = function (start, end, task) {
    return task.type == gantt.config.types.milestone ? 'milestone_popup' : '';
  };
  gantt.templates.quick_info_title = function (start, end, task) {
    return task.text;
  };

  gantt.templates.quick_info_date = function (start, end) {
    return `计划时间：${gantt.templates.tooltip_date_format(start)} 至 ${gantt.templates.tooltip_date_format(end)}`;
  };
  gantt.templates.quick_info_content = function (start, end, task) {
    return `
      <div>
          负责人 : ${gantt.templates.tooltip_date_format(start)}<br/>
          完成进度 : ${(task.progress || 0) * 100}%<br/>
          实际开始时间 : ${gantt.templates.tooltip_date_format(end)}<br/>
          实际完成时间 : <span style="color:red">未完成</span><br/>
      </div>
    `;
  };
  gantt.templates.tooltip_text = function (start, end, task) {
    return (
      task.text +
      `<br/><div>开始:${gantt.templates.tooltip_date_format(start)}</div>
       <div>结束:${gantt.templates.tooltip_date_format(end)}</div> `
    );
  };
  gantt.init(ganttRef.value);
  gantt.parse(tasks);
};
gantt.config.show_errors = false;

// gantt.deleteTask = () => {
//   return true
// }
// gantt.attachEvent('onTaskDblClick', (id: string) => {
//   console.log(id);
//   alert(1);
//   return false;
// });

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-ignore
window.addTask = (event) => {
  event.stopPropagation();
  event.stopImmediatePropagation();
  console.log('添加任务');
  alert('添加任务');
};
onMounted(() => {
  initGantt();
});
onUnmounted(() => {
  gantt.destructor();
});
gantt.config.autosize = false;
gantt.attachEvent('onAfterTaskUpdate', function (id, item) {
  // alert(JSON.stringify(item))
  // 将更新后的任务数据发送到服务器
  // gantt.server_pdata(item, "update"); // 或者使用 AJAX 方法发送数据
});
gantt.attachEvent('onAfterTaskDelete', (id) => {
  // alert(id)
  // this.$emit('link-updated', { id, action: 'delete' })
});
gantt.attachEvent('onAfterLinkUpdate', function (id, item) {
  // alert(JSON.stringify(item))
  // 将更新后的任务数据发送到服务器
  // gantt.server_pdata(item, "update"); // 或者使用 AJAX 方法发送数据
});
gantt.attachEvent('onAfterLinkDelete', function (id, item) {
  // alert(JSON.stringify(item))
  // 将更新后的任务数据发送到服务器
  // gantt.server_pdata(item, "update"); // 或者使用 AJAX 方法发送数据
});
</script>
<style lang="scss"></style>
